<template>
  <div>
    <my-header
      ><el-breadcrumb-item>公益管理</el-breadcrumb-item>
      <el-breadcrumb-item>公益分类</el-breadcrumb-item></my-header
    >

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7"
          ><!-- 输入框 -->
          <el-input
            placeholder="请输入公益事件"
            v-model="inputValue"
            clearable
            @clear="getPublicList"
          >
            <template #append>
              <el-button icon="Search" @click="onSearchList" />
            </template> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addDialogVisible = true"
            >添加公益事件</el-button
          ></el-col
        >
      </el-row>

      <!-- 公益列表区域 -->
      <el-table :data="publiclist" style="width: 100%" row-key="id" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="name" label="公益名称"></el-table-column>
        <el-table-column prop="parentid" label="所属分类"></el-table-column>
        <el-table-column prop="point" label="积分"></el-table-column>
        <el-table-column prop="remark" label="备注" width="600px">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top">
              <p class="showOverTooltip">{{ scope.row.remark }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="person" label="已参与人数"></el-table-column>
        <el-table-column label="图片">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="'http://192.168.101.65:9000' + scope.row.pic"
              :fit="fit"
              @click="lookDetail(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="showEditDialog(scope.row.id)"
            />
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="Delete"
              size="small"
              @click="removePublicById(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :page-sizes="[1, 2, 5, 10]"
        small="small"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="publiclist.length"
      />
    </el-card>

    <!-- 添加公益事件的对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加公益" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        status-icon
        :rules="addFormRules"
        label-width="90px"
      >
        <el-form-item label="公益名称" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input v-model="addForm.point" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" />
        </el-form-item>
        <el-form-item label="图片" prop="pic">
          <el-upload
            list-type="picture-card"
            :limit="1"
            show-file-list
            :auto-upload="false"
            :on-change="changePic"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属分类" prop="parentid">
          <el-select v-model="value" placeholder="选择所属分类">
            <el-option
              v-for="item in parentlist"
              :key="item.value"
              :label="item.cateName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addPublic">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改公益事件的对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改公益" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        status-icon
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="公益名称" prop="name">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input v-model="editForm.point" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editPublicInfo">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { publicList, addPublic, updatePublic, deletePublic } from '../../api/public.js'
export default {
  data() {
    // 验证积分的正则表达式
    const checkPoint = (rule, value, cb) => {
      const regPoint = /^([1-9][0-9]|[1-9][0-9][0-9]|1000)$/
      if (regPoint.test(value)) {
        return cb()
      }
      cb(new Error('注意：积分范围在 10 ~ 1000 的正整数！'))
    }
    return {
      inputValue: '',
      publiclist: [],
      parentlist: [],
      // 控制添加公益事件对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改公益事件对话框的显示与隐藏
      editDialogVisible: false,
      // 添加公益事件的表单数据
      addForm: { name: '', point: '', remark: '' },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [{ required: true, message: '请输入公益名称', trigger: 'blur' }],
        point: [
          { required: true, message: '请输入积分', trigger: 'blur' },
          { validator: checkPoint, trigger: 'blur' }
        ],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      // 查询到的公益信息
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        point: [
          { required: true, message: '请输入公益积分', trigger: 'blur' },
          { validator: checkPoint, trigger: 'blur' }
        ],
        remark: [{ required: true, message: '请输入公益备注', trigger: 'blur' }]
      },
      // 查看公益详情
      lookForm: {},
      lookDialogVisible: false,
      formData: '',
      formData1: '',
      value: ''
    }
  },
  created() {
    this.getPublicList()
  },
  methods: {
    changePic(file) {
      this.formData = new FormData()
      this.formData.append('filedata', file.raw)
    },
    changePic1(file) {
      this.formData1 = new FormData()
      this.formData1.append('filedata', file.raw)
    },
    onSearchList() {
      this.publiclist = this.publiclist.filter((item) => item.name.includes(this.inputValue))
    },
    async getPublicList() {
      this.publiclist = []
      const { data: res } = await publicList()
      if (res.code !== 1) {
        return this.$message.error('获取公益列表失败')
      }
      // 获取父级分类
      for (const item of res.data) {
        this.parentlist.push({ id: item.id, cateName: item.name })
      }

      // 获取具体的公益事件
      for (const item of res.data) {
        if (item.childrenTreeNodes) {
          for (const item1 of item.childrenTreeNodes) {
            item1.parentid = this.parentlist.find((con) => con.id === item1.parentid).cateName
            this.publiclist.push(item1)
          }
        }
      }
    },
    // 监听 switch 开关状态的改变
    async publicStateChanged(publicinfo) {
      const { data: res } = await updatePublic(publicinfo)
      if (res.code !== 1) {
        publicinfo.status = !publicinfo.status
        return this.$message.error('更新公益状态失败！')
      }
      this.$message.success('更新公益状态成功！')
    },
    // 监听添加公益事件对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新公益
    async addPublic() {
      const parent = this.value
      const params = {
        name: this.addForm.name,
        point: this.addForm.point,
        remark: this.addForm.remark,
        parent: parent,
        filedata: this.formData
      }
      const { data: res } = await addPublic(params)
      if (res.code !== 1) {
        this.$message.error('添加公益失败！')
      }
      this.getPublicList()
      // 隐藏添加公益的对话框
      this.$message.success('添加公益成功！')
      // 重新获取公益列表数据
      this.addDialogVisible = false
    },
    // 展示编辑公益的对话框
    async showEditDialog(id) {
      this.editForm = this.publiclist.find((item) => item.id === id)
      this.editDialogVisible = true
    },
    // 监听修改公益对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改公益信息并提交
    editPublicInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改公益信息的数据请求
        const { data: res } = await updatePublic(this.editForm)
        if (res.code !== 1) {
          return this.$message.error('更新公益信息失败！')
        }
        // 刷新数据列表
        this.getPublicList()
        // 关闭对话框
        this.editDialogVisible = false
        // 提示修改成功
        this.$message.success('更新公益信息成功！')
      })
    },
    // 根据id删除对应的公益信息
    async removePublicById(id) {
      // 弹框询问公益是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该公益，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await deletePublic(id)
      if (res.code !== 1) {
        return this.$message.error('删除公益失败！')
      }
      this.$message.success('删除成功！')
      this.getPublicList()
    },
    // 查看公益详情
    lookDetail(item) {
      this.lookForm = item
      this.lookDialogVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.showOverTooltip {
  display: -webkit-box;
  text-overflow: ellipsis;
  overflow: hidden;
  /*这里是3行*/
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.el-tooltip__popper {
  max-width: 400px !important;
  line-height: 180%;
}
</style>
